package com.etop.weiway.wxmanage.service;

import com.etop.weiway.basic.service.BaseService;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.dao.*;
import com.etop.weiway.wxmanage.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by KyLeo on 2014/12/29.
 */
@Service("AutoReplyService")
public class AutoReplyService extends BaseService {
    @Autowired
    private AutoReplyDAO autoReplyDAO;

    /**
     * 根据公众号ID获取消息列表
     *
     * @param pager
     * @param accountId
     * @return
     */
    public Pager<AutoReply> getAutoReplyListByAccountId(Pager<AutoReply> pager, Integer accountId, String keyword) throws Exception {
        log.debug("*************根据公众号ID获取消息列表**************");
        Map<String, Object> params = createParamMap();
        params.put("accountId", accountId);
        String queryString = "from AutoReply t where t.valid = 1 and t.account.id = :accountId";
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.keyWord like :keyword )";
            params.put("keyword", getKeyWords(keyword));
        }
        String orderString = " order by t.orderId asc";
        queryString += orderString;
        List<AutoReply> autoReplys = autoReplyDAO.find(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(autoReplyDAO.getTotalCount(queryString, params));
        pager.setList(autoReplys);
        return pager;
    }

    /**
     * 根据自动回复id来查询
     *
     * @param id
     * @return
     */
    public AutoReply findAutoReplyById(Integer id) throws Exception {
        log.debug("***************根据自动回复id来查询*****************");
        return autoReplyDAO.get(id);
    }

    /**
     * 保存自动回复
     *
     * @param autoReply
     * @param accountId
     */
    public void saveAutoReply(AutoReply autoReply, Integer accountId) throws Exception {
        log.debug("*************保存自动回复**************");
        Account account = new Account();
        account.setId(accountId);
        autoReply.setAccount(account);
        autoReplyDAO.save(autoReply);
    }

    /**
     * 更新自动回复
     *
     * @param autoReply
     * @param accountId
     * @throws Exception
     */
    public void updateAutoReply(AutoReply autoReply, Integer accountId) throws Exception {
        log.debug("*************更新自动回复**************");
        Account account = new Account();
        account.setId(accountId);
        autoReply.setAccount(account);
        autoReplyDAO.update(autoReply);
    }

    /**
     * 根据ID来删除自动回复
     *
     * @param id
     */
    public void deleteAutoReplyById(Integer id) throws Exception {
        log.debug("*************根据ID来删除自动回复**************");
        autoReplyDAO.deleteById(id);
    }
}
